<?php
/*
 * @Date: 2020-05-25 16:38:55
 * @名称: 
 * @版本: 0.01
 * @作者: 初雪桜
 * @邮箱: 202184199@qq.com
 * @最后编辑人: 初雪桜
 * @LastEditTime: 2021-03-01 00:04:40
 * @FilePath: /Site/app/useradmin/controller/CreateComics.php
 */

namespace app\useradmin\controller;

use app\BaseController;
use think\facade\Db;
use app\useradmin\controller\DataBaseController\AuthorAndChineseTeam;
use app\useradmin\controller\DataBaseController\LogController;

class CreateComics extends BaseController
{
    public function CreateComics() //创建漫画
    {
        $token = cookie("Authorization");;
        $userTokenVerificationParse = ParseUserToken($token, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];

        $time =  time();
        $hashHmac_toKen = [
            "time" => $time, //超时六十分钟过期
            "hashHmac_token" => hash_hmac('sha256', $user_info['_id'] . $token . $time, config("useradminConfig.useradmin_CreateComicsKey")),
        ];
        $classified_catalogueList = Db::table('classified_catalogue')
            ->field([
                "title"
            ])
            ->where([
                "state" => 1
            ])
            ->select();
        foreach ($classified_catalogueList as $key => $value) {
            $classified_catalogue[$key] = [
                "name" => $value["title"],
                "value" => $value["title"],
                "selected" =>  false,
            ];
        }
        return  view(
            'CreateComics/CreateComics',
            [
                "classified_catalogue" => json_encode($classified_catalogue),
                "useradmin" => config("useradminConfig.useradmin_serverHost"),
                "time" => $time,
                "hashHmac_toKen" => authcode(json_encode($hashHmac_toKen), 'encode', config("useradminConfig.useradmin_Edit_EditComicsInfo_sha256Encryption")), //!解密传入的用户信息,
            ]
        );
    }
    public function SeverComics()
    # 保存创建的漫画
    {
        $token = cookie("Authorization");;
        $userTokenVerificationParse = ParseUserToken($token, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];

        #用户信息
        $projectname = input('post.projectname');
        #漫画名称
        $ComicsInfo = input('post.ComicsInfo');
        #详细信息
        $comment = input('post.comment');
        #评论开关
        $download = input('post.download');
        #下载开关
        $hashHmac_toKen = input('post.hashHmac_toKen');
        #验证token
        $comicsClass = input("post.comicsClass");
        #分类 需要验证是否为空
        $comicsTags = input("post.comicsTags");
        #标签
        $book_id = randIdStructure(4);
        #书籍id
        $aacto_id = randIdStructure(1);
        #作者操作表id
        $search = array(" ", "　", "\n", "\r", "\t");
        $replace = array("", "", "", "", "");
        $classStr = '';
        #分类
        $tagsStr = '';
        #标签
        if (gettype($projectname) != 'string') { //判断扩展类型是不是文本
            return errorJsonReturn("Missing parameter", __LINE__);
            #标题类型不是文本
        }
        if (gettype($ComicsInfo) != 'string') { //判断扩展类型是不是文本
            return errorJsonReturn("Missing parameter", __LINE__);
            #标题类型不是文本
        }
        if ($comment != 'true' && $comment != 'false') { //判断开关状态
            return errorJsonReturn("Missing parameter", __LINE__);
            #标题类型不是文本
        }
        if ($download != 'true' && $download != 'false') { //判断开关状态
            return errorJsonReturn("Missing parameter", __LINE__);
            #标题类型不是文本
        }
        if (!str_replace($search, $replace, $projectname)) {
            return errorJsonReturn("Missing parameter", __LINE__);
            #标题为空
        }
        if (!str_replace($search, $replace, $ComicsInfo)) {
            return errorJsonReturn("Missing parameter", __LINE__);
            #相信信息为空
        }
        if (!is_array($comicsClass)) {
            return errorJsonReturn("Missing parameter", __LINE__);
            #漫画分类不是正确的array类型
        }
        if (!is_array($comicsTags)) {
            return errorJsonReturn("Missing parameter", __LINE__);
            #漫画标签不是正确的array类型
        }
        /* 开始解析 hashHmac_toKen */
        $ParseHashHmac_toKen = json_decode(authcode($hashHmac_toKen, 'DECODE', config("useradminConfig.useradmin_Edit_EditComicsInfo_sha256Encryption")), true);
        #!解密传入的用户信息,
        /* $ParseHashHmac_toKen = {
    "time": //加密的时间戳
    "hashHmac_token"://验证字符串
    } */
        //验证有没有超时
        if ($ParseHashHmac_toKen['time'] + 3600  < time()) {
            return errorJsonReturn("time Out");
            #用户token验证失败 提交的token 和验证的token不一个
        }
        // 验证token
        $hashHmac_toKen =  hash_hmac('sha256', $user_info['_id'] . $token .  $ParseHashHmac_toKen['time'], config("useradminConfig.useradmin_CreateComicsKey"));
        if ($hashHmac_toKen != $ParseHashHmac_toKen['hashHmac_token']) {
            return errorJsonReturn("Failed to resolve user");
            #用户token验证失败 提交的token 和验证的token不一个
        }
        // 查询分类
        $DataBaseClassList = Db::table('classified_catalogue')
            ->where([
                'enable' => 1,
            ])
            ->field([
                "title",
                '_id'
            ])
            ->select();
        $classList = [];
        foreach ($DataBaseClassList as $key => $value) {
            $classList[$value['title']] = $value['_id'];
        } //吧数组下面的val变为key
        foreach ($comicsClass as $key => $value) {
            if (!isset($classList[$value['name']])) {
                return errorJsonReturn('An exception occurred in the classification you submitted', "请刷新网页再试");
                exit;
            }
        }

        //!插入分类数据库
        foreach ($comicsClass as $key => $value) {
            try {
                Db::table("book_info_categories_info_" . $classList[$value['name']])
                    ->insert([
                        "_id" => randIdStructure(3), //表id
                        "book_id" =>  $book_id,
                        "state" => 1,
                        "add_user_id" => $user_info["_id"],
                        "add_time" => date("Y-m-d H:i:s")
                    ]);
                $classStr .= ",$value[name]";
            } catch (\Throwable $th) {
                //插入错误 一般都是 没有找到数据库
            }
        }

        foreach ($comicsTags as $key => $value) {
            $tagsStr .= ",$value[value]";
        }
        $classStr = substr($classStr, 1); //删除classStr 第一个字符
        $tagsStr = substr($tagsStr, 1); //删除tagsStr 第一个字符
        if (!$classStr) {
            return errorJsonReturn('分类错误 分类不可选择 或不存在 ');
        }
        //插入数据库 book_list
        Db::table("book_list")
            //插入漫画
            ->insert([
                "title" => ltrim($projectname),
                "author" => '测试作者',
                "file_server" => 'https://i0.hdslb.com/',
                "path" => "bfs/album/619fe3ebc7c8c1f0dcd9494c8c5d2d4b29e60a85.jpg",
                "original_name" => 'cover.jpg',
                "_id" => $book_id,
                "user_id" => $user_info['_id'],
                "created_at" => date(DATE_ISO8601, strtotime(date("Y-m-d H:i:s"))),
            ]);
        Db::table('book_info')
            #插入相信信息
            ->insert(
                [
                    "_id" => $book_id, //* 书籍id
                    "description" =>   $ComicsInfo, //* 简介
                    "categories" =>  $classStr, //* 分类
                    "tags" =>  $tagsStr, //* 标签
                    "pages_count" =>  0, //* 总页数
                    "eps_count" =>  0, //* 总图片数量
                    "finished" =>  0, //* 已完结
                    "updated_at" =>  date(DATE_ISO8601, strtotime(date("Y-m-d H:i:s"))), //* 更新时间
                    "allow_download" =>  $download, //* 允许下载
                    "allow_comment" => $comment, //* 允许评论
                    "total_views" => 0, //* 总页数
                    "total_likes" =>  0, //* 喜欢人数
                    "views_count" =>  0, //* 查看人数
                    "likes_count" =>  0, //* 喜欢人数
                    "is_favourite" =>  0, //* 是否是我喜欢的
                    "comments_count" =>  0, //* 评论数
                    "success" => 0, //* 爬虫是否成功
                ]
            );
        Db::table('author_and_chinese_team')
            #插入作者信息
            ->insert([
                "book_id" => $book_id,
                #书籍id
                "user_id" =>  $user_info["_id"],
                #用户id
                "author_or_chinese_team" => 0,
                #状态作者 0/协作者 1
                "add_time" => date("Y-m-d H:i:s"),
                #插入时间
                "insert_name_id" =>  $user_info["_id"],
                #插入人id/更改人id
                "state" => 0,
                #状态 0正常 1已停用
                "_id" => $aacto_id,
                #操作id
                "edit_delete_user" => 1,
                #允许删除用户
                "edit_inherit_users" => 1,
                #是否允许继承用户
                "edit_edit_user" => 1,
                #编辑用户
                "edit_add_user" => 1,
                #增加用户
                "edit_sever_comics_info" => 1,
                #是否允许保存修改漫画信息
            ]);
        $LogController = new LogController($this->app);
        $LogController->insert_AACT_log(
            $book_id,
            $user_info["_id"],
            $user_info["_id"],
            $aacto_id,
            "用户id $user_info[_id] 在 " . date("Y-m-d H:i:s") . '创建了这篇漫画',
            1,
            $user_info["_id"],
            [
                "implement_time" => date("Y-m-d H:i:s"), //执行时间
                "implement_user_id" => $user_info["_id"], //执行者
            ]
        );
       
    }
    public function recoveryComics()
    #恢复漫画
    {
        $user_info = config("globalsettings.user_info"); //用户信息

        $book_id = input("post.bookId");
        $title = input("post.title");
        $token = cookie("Authorization");
        $userTokenVerificationParse = ParseUserToken($token, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];
        unset($userTokenVerificationParse);
        $AuthorAndChineseTeam = new AuthorAndChineseTeam($this->app);
        $PermissionQuery =  $AuthorAndChineseTeam->Select($user_info['_id'], $book_id, ['author_or_chinese_team']); //查询用户权限
        if ($PermissionQuery['code'] != 200) { //判断权限是否正常
            return $PermissionQuery; //用户状态不正常
        } else {
            if ($PermissionQuery['data']['author_or_chinese_team'] == 1) { //判断我是不是作者 0是创作者 1是协作者 创作者有 删除 / 恢复 权限
                return errorJsonReturn('Insufficient user rights');
            }
        }
        unset($PermissionQuery);


        $book_info =  Db::table('book_list')
            #查询当前文章状态
            ->where([
                "_id" => $book_id,
                "delete" => 0, //没有被删除的
                "title" => $title,
                "state" => 0, //漫画状态 0异常 1 正常
                "exp_state" => 2, //扩展状态 在状态 异常的情况下判断这个 扩展状态 1待站长审核 2待删除
            ])
            ->find();
        if (!$book_info) {
            return errorJsonReturn('Comics Abnormal state', '漫画状态异常 请刷新重试');
        }
        //更新漫画状态 
        try {
            $book_info =  Db::table('book_list')
                #查询当前文章状态
                ->where([
                    "_id" => $book_id,
                    "delete" => 0, //没有被删除的
                    "title" => $title,
                    "state" => 0, //漫画状态 0异常 1 正常
                    "exp_state" => 2, //扩展状态 在状态 异常的情况下判断这个 扩展状态 1待站长审核 2待删除
                ])
                ->update([
                    "state" => 1,
                    "exp_state" => null, //扩展状态 在状态 异常的情况下判断这个 扩展状态 1待站长审核 2待删除
                ]);
            if ($book_info) {
                Db::table("log_book_list")
                    ->insert([
                        "_id" => $book_id,
                        "title" => $title,
                        "msg" => "用户 $user_info[_id] 将 <a style='color:#9cdcfe'>$title</a>  恢复了",
                        "insert_user_id" => $user_info["_id"],
                    ]);
            }
            return successJsonReturn('success');
        } catch (\Throwable $th) {
            return errorJsonReturn('undefined Error', '发生意外错误 刷新重试');
        }
    }
    public function DeleteComics()
    #删除漫画
    {

        $book_id = input("post.bookId");
        $title = input("post.title");
        $token = cookie("Authorization");
        $userTokenVerificationParse = ParseUserToken($token, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];
        $AuthorAndChineseTeam = new AuthorAndChineseTeam($this->app);
        $PermissionQuery =  $AuthorAndChineseTeam->Select($user_info['_id'], $book_id, ['edit_delete_comics']); //查询是否有删除漫画的权限
        if ($PermissionQuery['code'] != 200) { //判断权限是否正常
            return $PermissionQuery; //用户状态不正常
        } else {
            if ($PermissionQuery['data']['edit_delete_comics'] != 1) { //判断我是不是有删除漫画的权限 0没有 1有
                return json_decode(errorJsonReturn("Comics-Delete-10000")->getContent(), true);
            }
        }
        unset($PermissionQuery);
        $book_info =  Db::table('book_list')
            #查询当前文章状态
            ->where([
                "_id" => $book_id,
                "delete" => 0, //没有被删除的
                "title" => $title,
                "state" => 1, //漫画状态 0异常 1 正常
            ])
            ->find();
        if (!$book_info) {
            return json_decode(errorJsonReturn("Comics-Delete-10001")->getContent(), true);
        }
        //更新漫画状态 
        try {
            $book_info =  Db::table('book_list')
                #查询当前文章状态
                ->where([
                    "_id" => $book_id,
                    "delete" => 0, //没有被删除的
                    "title" => $title,
                    "state" => 1, //漫画状态 0异常 1 正常
                ])
                ->update([
                    "state" => 0,
                    "exp_state" => 2, //扩展状态 在状态 异常的情况下判断这个 扩展状态 1待站长审核 2待删除
                ]);
            if ($book_info) {
                Db::table("log_book_list")
                    ->insert([
                        "_id" => $book_id,
                        "title" => $title,
                        "msg" => "用户 $user_info[_id] 将 <a style='color:red'>$title</a>  删除了",
                        "insert_user_id" => $user_info["_id"],
                    ]);
            }
            return successJsonReturn('success');
        } catch (\Throwable $th) {
            return errorJsonReturn('undefined Error', '发生意外错误 刷新重试');
        }
    }
    public function EnterDeleteComics()
    #确认永久删除漫画
    {
        $token = cookie("Authorization");;
        $userTokenVerificationParse = ParseUserToken($token, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];


        $book_id = input("post.bookId");
        $title = input("post.title");
        $token = input("post.token");
        $AuthorAndChineseTeam = new AuthorAndChineseTeam($this->app);
        $PermissionQuery =  $AuthorAndChineseTeam->Select($user_info['_id'], $book_id, ['author_or_chinese_team']); //查询用户权限
        if ($PermissionQuery['code'] != 200) { //判断权限是否正常
            return $PermissionQuery; //用户状态不正常
        } else {
            if ($PermissionQuery['data']['author_or_chinese_team'] == 1) { //判断我是不是作者 0是创作者 1是协作者 创作者有 删除 / 恢复 权限
                return errorJsonReturn('Insufficient user rights');
            }
        }
        unset($PermissionQuery);
        $deleteComicsInfo =  Db::table('book_info') //删除漫画列表 里的记录
            ->where([
                "_id" => $book_id,
            ])
            ->find();
        $classList = explode(",", $deleteComicsInfo['categories']);
        //查询所有分类
        $CC = Db::table("classified_catalogue")
            ->select();
        $classified_catalogue = [];
        foreach ($CC as $key => $value) {
            //把所有分类 变为 名字 =》 id
            $classified_catalogue[$value['title']] = $value['_id'];
        }
        foreach ($classList as $key => $value) {
            Db::table("book_info_categories_info_$classified_catalogue[$value]")
                ->where([
                    "book_id" => $book_id,
                ])
                ->delete();
        }
        Db::table('book_list') //删除漫画列表 里的记录
            ->where([
                "_id" => $book_id,
                "title" => $title,
            ])
            ->delete();
        Db::table('book_info') //删除漫画详细信息 里的记录
            ->where([
                "_id" => $book_id,
            ])
            ->delete();
        Db::table('author_and_chinese_team') //作者表 里的记录
            ->where([
                "_id" => $book_id,
            ])
            ->delete();
        Db::table('author_and_chinese_team_operation') //作者表操作 里的记录
            ->where([
                "_id" => $book_id,
            ])
            ->delete();
        Db::table('book_comment') //评论表 里的记录
            ->where([
                "book_id" => $book_id,
            ])
            ->delete();

        $deleteComicsAllProject =  Db::table('book_info_project') //删除分卷表 里的记录
            ->where([
                "_id" => $book_id,
            ])
            ->select();
        foreach ($deleteComicsAllProject  as $key => $value) { //删除所有我上传的图片
            if ($value["database_table_name"]) { //查询漫画当前章节的图片的表
                $imageList = Db::table($value["database_table_name"])
                    ->where([
                        "_id" => $book_id,
                        "project_id" => $value["chapter_id"],
                    ])
                    ->select();
                Db::table($value["database_table_name"])
                    ->where([
                        "_id" => $book_id,
                        "project_id" => $value["chapter_id"],
                    ])
                    ->delete();
                foreach ($imageList as $key => $value) { //删除当前漫画文件
                    unlink($value['path']);
                }
            }
        }
        Db::table('book_info_project') //删除分卷表 里的记录
            ->where([
                "_id" => $book_id,
            ])->delete();
        Db::table("log_book_list")
            ->insert([
                "_id" => $book_id,
                "title" => $title,
                "msg" => "用户 $user_info[_id] 将 <a style='color:red'>$title</a>  永久删除了",
                "insert_user_id" => $user_info["_id"],
            ]);
        return successJsonReturn('success');
    }
}
